using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using SPL.Services;
using SPL.Entities;

public partial class Login : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Session.Clear();
    Session.Abandon();
    FormsAuthentication.SignOut();
  }

  protected void btnGo_Click(object sender, System.EventArgs e)
  {
    UserService us = new UserService();
    TList<SPL.Entities.User> users = us.GetByWhereClause("Username='" + this.login_user_email.Value.Trim().ToLower() + "'", "");
    us.DeepLoad(users, true, SPL.Data.DeepLoadType.IncludeChildren, typeof(Role), typeof(Department));

    if (users != null && users.Count > 0 && 
      users[0].Password.Equals(this.login_user_password.Value.Trim(), StringComparison.OrdinalIgnoreCase))
    {
      // Success, create non-persistent authentication cookie.

      FormsAuthentication.SetAuthCookie(users[0].Username, false);

      FormsAuthenticationTicket ticket1 =
         new FormsAuthenticationTicket(
              1,                                   // version
              users[0].Username,
              DateTime.Now,                        // issue time is now
              DateTime.Now.AddMinutes(3600),         // expires
              false,      // cookie is not persistent
              users[0].RoleIdSource.Value.Value.ToString() + "|" + users[0].DeptIdSource.Value.Value.ToString() + "|" + users[0].Id.ToString()
              );

      HttpCookie cookie1 = new HttpCookie(
        FormsAuthentication.FormsCookieName,
        FormsAuthentication.Encrypt(ticket1));
      Response.Cookies.Add(cookie1);

      String returnUrl1;
      // the login is successful
      if (Request.QueryString["ReturnUrl"] == null)
      {
        returnUrl1 = "default.aspx";
      }
      //login not unsuccessful 

      else
      {
        returnUrl1 = Request.QueryString["ReturnUrl"];
      }
      Response.Redirect(returnUrl1);
    }
  }


}
